package com.android.systemui.statusbar.board;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.android.systemui.R;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

import static android.content.Context.WIFI_SERVICE;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHERNET_STATIC_DNS1;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHERNET_STATIC_DNS2;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHERNET_STATIC_GATEWAY;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHERNET_STATIC_IP;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHERNET_STATIC_NETMASK;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHER_STATE_CONNECTED;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHER_STATE_CONNECTING;
import static com.android.systemui.statusbar.board.EthernetUtil.ETHER_STATE_DISCONNECTED;

import java.util.*;

import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.content.ComponentName;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;

public class InternetDialog extends BaseDialog
        implements CompoundButton.OnCheckedChangeListener, TextView.OnEditorActionListener,
        View.OnClickListener {

    private static final String TAG = "Board---InternetDialog";
    RadioButton rbWirelessNetwork;
    RadioButton rbWiredNetwork;
    LinearLayout llWirelessNetwork;
    LinearLayout llWiredNetwork;

    ToggleButton tbWifiSwitch;
    RelativeLayout rlWifiSwitch;
    ListView rvWifiList;
    LinearLayout llWifiContent;
    View viewWifiNoOpen;
    LinearLayout rlWifiContent;
    TextView tvConfirmWifiPassword;
    TextView tvCancelWifiPassword;
    FloatingKeyboardView keyboard;
    RelativeLayout rlWifiConnectingContent;
    EditText etPasswordWifi;
    TextView tvWifiConnectingSsid;

    ToggleButton tbOpenHotspot;
    ToggleButton tbAutoIp;
    EditText etIpAddress;
    EditText etSubnetMask;
    EditText etGateway;
    EditText etDns1;
    EditText etDns2;
    RelativeLayout rlKeyboard;
    FloatingKeyboardView fkKeyboard;
    RelativeLayout rlCaution;

    RelativeLayout reBreakWifi;
    TextView tv_wifi_break;
    TextView tv_confirm_break;
    TextView tv_cancel_break;
    TextView wifi_list_tip;

    private static final int WIFI_OPEN_FINISH = 1;//开启完成
    private static final int REFRESH_WIFI_STATUS = 0;//刷新wifi页面
    private static final int WIFI_SCAN = 2;//wifi扫描
    private static final int WIFI_CLOSE = 3;//关闭wifi
    private static final int WIFI_INFO = 4;
    private static final int WIFI_STATE_INIT = 5;//加载页面
    private List<ScanResult> scanResults = new ArrayList<>();
    private WiFiAdmin wiFiAdmin;
    private String connectSSID = "";
    private WifiListAdapter wifiListAdapter;

    private long[] mHints = new long[7];
    private Handler handler;

    public static final String WIRED_NETWORK_SWITCH = "wired_network_switch";
    public static final String OPEN_HOTSPOT_SWITCH = "open_hotspot_switch";
    public static final String AUTO_IP_SWITCH = "auto_ip_switch";

    private EthernetUtil ethernetUtil;
    private WifiApManager wifiApManager;

    private boolean isInit = true;

    private Intent brushIntent;

    private Timer timer;

    private RefreshWifiTask refreshWifiTask;

    private final String WIFI_GETTING_LIST = mContext.getString(R.string.wifi_getting_list);
    private final String WIFI_LIST = mContext.getString(R.string.wifi_list);
    private final String WIFI_GETTING_IP = mContext.getString(R.string.wifi_getting_ip);

    private static class WifiHandler extends Handler {
        WeakReference<InternetDialog> mWeakReference;
        private final String WIFI_GETTING_LIST;
        private final String WIFI_LIST;
        private final String WIFI_GETTING_IP;

        WifiHandler(InternetDialog popup) {
            mWeakReference = new WeakReference<>(popup);
            WIFI_GETTING_LIST = popup.mContext.getString(R.string.wifi_getting_list);
            WIFI_LIST = popup.mContext.getString(R.string.wifi_list);
            WIFI_GETTING_IP = popup.mContext.getString(R.string.wifi_getting_ip);
        }

        @Override
        public void handleMessage(Message msg) {
            final InternetDialog internetPopup = mWeakReference.get();
            switch (msg.what) {
                case REFRESH_WIFI_STATUS:
                    internetPopup.wiFiAdmin.StartScan();
                    if (internetPopup.wiFiAdmin.getWifiManager().getScanResults().size() == 0) {
                        internetPopup.wifi_list_tip.setText(WIFI_GETTING_LIST);
                    } else {
                        internetPopup.wifi_list_tip.setText(WIFI_LIST);
                    }
                    internetPopup.resetData(internetPopup.wiFiAdmin.getWifiManager().getScanResults());
                    internetPopup.wifiListAdapter.setConnectedBSSID(internetPopup.getNowWifiBSSID());
                    break;
                case WIFI_STATE_INIT:
                    int wifiState = internetPopup.wiFiAdmin.GetWifiState();
                    if (wifiState == WifiManager.WIFI_STATE_DISABLED) {  //wifi不可用啊
                        internetPopup.tbWifiSwitch.setChecked(false);
                    } else if (wifiState == WifiManager.WIFI_STATE_UNKNOWN) {//wifi 状态未知
                        internetPopup.tbWifiSwitch.setChecked(false);
                    } else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {//OK 可用
                        internetPopup.tbWifiSwitch.setChecked(true);
                    }
                    break;
                case WIFI_OPEN_FINISH:
                    internetPopup.resetData(internetPopup.wiFiAdmin.GetWifilist());
                    break;
                case WIFI_SCAN:
                    internetPopup.wiFiAdmin.StartScan();
                    internetPopup.resetData(internetPopup.wiFiAdmin.GetWifilist());
                    if (internetPopup.scanResults == null) {
                        internetPopup.handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000);
                    } else if (internetPopup.scanResults.size() == 0) {
                        internetPopup.handler.sendEmptyMessageDelayed(WIFI_SCAN, 1000);
                        internetPopup.setScanResult();
                    } else {
                        internetPopup.wifiListAdapter.notifyDataSetChanged();
                        internetPopup.handler.sendEmptyMessageDelayed(WIFI_INFO, 1000);
                    }
                    break;
                case WIFI_CLOSE:
                    internetPopup.setScanResult();
                    break;
                case WIFI_INFO:
                    internetPopup.wiFiAdmin.getWifiConnectInfo();
                    if (internetPopup.wiFiAdmin.GetSSID().endsWith("<unknown ssid>")
                            || internetPopup.wiFiAdmin.GetSSID().endsWith("NULL")) {
                        internetPopup.handler.sendEmptyMessageDelayed(WIFI_INFO, 2500);
                    } else {
                        internetPopup.connectSSID = internetPopup.wiFiAdmin.GetSSID();
                        if (internetPopup.wiFiAdmin.GetIntIp().equals("")) {
                            internetPopup.handler.sendEmptyMessageDelayed(WIFI_INFO, 2500);
                            internetPopup.wifiListAdapter.setConnectingDescription(
                                    internetPopup.wiFiAdmin.GetBSSID(), WIFI_GETTING_IP);
                            internetPopup.wifiListAdapter.notifyDataSetChanged();
                        } else {
                            //connect success
                            internetPopup.wifiListAdapter.setConnectedBSSID(
                                    internetPopup.getNowWifiBSSID());
                            if (internetPopup.wiFiAdmin.GetSSID().contains("Eloam")) {
                                Intent openEloam = new Intent("com.w2here.board.open_eloam");
                                openEloam.putExtra("wifiId", internetPopup.wiFiAdmin.getWifiConnectInfo().getNetworkId());
                                internetPopup.mContext.sendBroadcast(openEloam);
                                internetPopup.dismiss();
                            }
                            internetPopup.refreshWifiState();
                        }

                    }
                    break;
                default:
                    break;

            }
            super.handleMessage(msg);
        }
    }

    InternetDialog(Context context) {
        super(context);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.pop_setting_internet;
    }

    @Override
    protected void initView(View view) {
        rbWirelessNetwork = (RadioButton) view.findViewById(R.id.rb_wireless_network);
        rbWiredNetwork = (RadioButton) view.findViewById(R.id.rb_wired_network);
        llWirelessNetwork = (LinearLayout) view.findViewById(R.id.ll_wireless_network);
        llWiredNetwork = (LinearLayout) view.findViewById(R.id.ll_wired_network);

        tbWifiSwitch = (ToggleButton) view.findViewById(R.id.tb_wifi_switch);
        rlWifiSwitch = (RelativeLayout) view.findViewById(R.id.rl_wifi_switch);
        rvWifiList = (ListView) view.findViewById(R.id.rv_wifi_list);
        llWifiContent = (LinearLayout) view.findViewById(R.id.ll_wifi_content);
        viewWifiNoOpen = view.findViewById(R.id.view_wifi_no_open);
        rlWifiContent = (LinearLayout) view.findViewById(R.id.rl_wifi_content);
        tvConfirmWifiPassword = (TextView) view.findViewById(R.id.tv_confirm_wifi_password);
        tvCancelWifiPassword = (TextView) view.findViewById(R.id.tv_cancel_wifi_password);
        keyboard = (FloatingKeyboardView) view.findViewById(R.id.keyboard);
        rlWifiConnectingContent = (RelativeLayout) view.findViewById(R.id.rl_wifi_connecting_content);
        etPasswordWifi = (EditText) view.findViewById(R.id.et_password_wifi);
        tvWifiConnectingSsid = (TextView) view.findViewById(R.id.tv_wifi_connecting_ssid);

        tbOpenHotspot = (ToggleButton) view.findViewById(R.id.tb_open_hotspot);
        tbAutoIp = (ToggleButton) view.findViewById(R.id.tb_auto_ip);
        etIpAddress = (EditText) view.findViewById(R.id.et_ip_address);
        etSubnetMask = (EditText) view.findViewById(R.id.et_subnet_mask);
        etGateway = (EditText) view.findViewById(R.id.et_gateway);
        etDns1 = (EditText) view.findViewById(R.id.et_dns1);
        etDns2 = (EditText) view.findViewById(R.id.et_dns2);
        rlKeyboard = (RelativeLayout) view.findViewById(R.id.rl_keyboard);
        fkKeyboard = (FloatingKeyboardView) view.findViewById(R.id.fk_keyboard);
        rlCaution = (RelativeLayout) view.findViewById(R.id.rl_caution);

        reBreakWifi = (RelativeLayout) view.findViewById(R.id.rl_wifi_break_content);
        tv_wifi_break = (TextView) view.findViewById(R.id.tv_wifi_break);
        tv_confirm_break = (TextView) view.findViewById(R.id.tv_confirm_break);
        tv_cancel_break = (TextView) view.findViewById(R.id.tv_cancel_break);
        wifi_list_tip = (TextView) view.findViewById(R.id.wifi_list_tip);

//        NotificationCenter.getInstance().addStickObserver(this, NotificationCenter.ethernetChanged);

        initData();
        handler.sendEmptyMessage(WIFI_STATE_INIT);
        rlWifiConnectingContent.setVisibility(View.GONE);
        reBreakWifi.setVisibility(View.GONE);
        keyboard.setPreviewEnabled(false); // NOTE Do not show the preview balloons
        keyboard.registerEditText(new EditText[]{etPasswordWifi});
        hideSystemInput(etPasswordWifi);
        initNetwork();

        //初始化以太网
        initWired();

        brushIntent = new Intent("com.w2here.board.controller_miracast");
        brushIntent.putExtra("is_close_miracast", true);
        mContext.sendBroadcast(brushIntent);
        refreshWifiState();
    }

    public void refreshWifiState() {
        if (null != handler) {
            if (null != timer) {
                timer.cancel();
                timer = null;
                refreshWifiTask.cancel();
                refreshWifiTask = null;
            }
            timer = new Timer();
            refreshWifiTask = new RefreshWifiTask();
            timer.schedule(refreshWifiTask, 10, 4000);
        }
    }

    private class RefreshWifiTask extends TimerTask {
        @Override
        public void run() {
            if (null != handler) {
                handler.sendEmptyMessage(REFRESH_WIFI_STATUS);
            }
        }
    }

    private void initNetwork() {
        rbWirelessNetwork.setChecked(true);
        rbWiredNetwork.setChecked(false);
        rbWirelessNetwork.setOnCheckedChangeListener(this);
        rbWiredNetwork.setOnCheckedChangeListener(this);
    }

    private void initData() {
        wifiApManager = new WifiApManager(mContext);
        wifiApManager.setWifiEnabled();
        handler = new WifiHandler(this);
        wiFiAdmin = new WiFiAdmin(mContext);
        wifiListAdapter = new WifiListAdapter(mContext);
        wifiListAdapter.setData(scanResults);
        wifiListAdapter.setConnectedBSSID(getNowWifiBSSID());
        rvWifiList.setAdapter(wifiListAdapter);
        rbWirelessNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1);//把从第二位至最后一位之间的数字复制到第一位至倒数第一位
                mHints[mHints.length - 1] = SystemClock.uptimeMillis();//从开机到现在的时间毫秒数
                if (SystemClock.uptimeMillis() - mHints[0] <= 2000) {//连续点击之间间隔小于一秒，有效
                    mHints = new long[7];
                    backDoor();
//                    Intent intent = new Intent(Settings.ACTION_SETTINGS);//系统设置界面
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    mContext.startActivity(intent);
                }
            }
        });

        rvWifiList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int index, long arg3) {
                ScanResult scanResult = (ScanResult) scanResults.get(index);
                if (scanResult.BSSID.equals(getNowWifiBSSID())) {
                    tv_wifi_break.setText(String.format(mContext.getString(R.string.str_wifi_beak), scanResult.SSID));
                    reBreakWifi.setVisibility(View.VISIBLE);
                    tv_cancel_break.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            reBreakWifi.setVisibility(View.GONE);
                        }
                    });
                    tv_confirm_break.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            wiFiAdmin.disconnectWifi(wiFiAdmin.getWifiConnectInfo().getNetworkId());
                            if (null != handler) {
                                handler.sendEmptyMessage(REFRESH_WIFI_STATUS);
                            }
                            reBreakWifi.setVisibility(View.GONE);
                        }
                    });

                } else {
                    String encryption = wifiListAdapter.getEncryption(scanResult.capabilities);
                    enableWifiPasswordScreen(scanResult.SSID, scanResult.BSSID, encryption);
                }
            }
        });

        tvCancelWifiPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rlWifiConnectingContent.setVisibility(View.GONE);
            }
        });

        //防止事件穿透
        rlWifiConnectingContent.setOnClickListener(this);

        setScanResult();
    }

    private void backDoor() {
        if (rlWifiConnectingContent == null) return;
        tvWifiConnectingSsid.setText(mContext.getString(R.string.input_password_please));
        rlWifiConnectingContent.setVisibility(View.VISIBLE);
        etPasswordWifi.setText("");
        etPasswordWifi.requestFocus();
        tvConfirmWifiPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals("board-Rk3288", etPasswordWifi.getText().toString())) {
                    rlWifiConnectingContent.setVisibility(View.GONE);
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    ComponentName cn = new ComponentName("com.android.engineermode",
                            "com.android.engineermode.MainActivity");
                    intent.setComponent(cn);
                    mContext.startActivity(intent);
                }
            }
        });
    }

    private void enableWifiPasswordScreen(final String ssid, final String Bssid, final String encryption) {
        tvWifiConnectingSsid.setText(String.format(
                mContext.getString(R.string.str_wifi_connecting_ssid), ssid));
        etPasswordWifi.setText("");
        etPasswordWifi.requestFocus();
        rlWifiConnectingContent.setVisibility(View.VISIBLE);

        //加密方式
        final int type;
        switch (encryption) {
            case "":
                type = 1;
                connectWifi(Bssid, ssid, type);
                break;
            case "WEP":
                type = 2;
                break;
            default:
                type = 3;
                break;
        }

        //键盘确认键
        etPasswordWifi.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE)
                    connectWifi(Bssid, ssid, type);
                return false;
            }
        });


        tvConfirmWifiPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectWifi(Bssid, ssid, type);
            }
        });
    }

    private void connectWifi(String Bssid, String ssid, int type) {
        if (null != timer) {
            timer.cancel();
        }
        wifiListAdapter.setConnectingDescription(Bssid, mContext.getString(R.string.wifi_connecting));
        wifiListAdapter.notifyDataSetChanged();
        String wifiPassword = etPasswordWifi.getText().toString();
        int netId = wiFiAdmin.AddNetwork(wiFiAdmin.CreateConfiguration(ssid, Bssid, wifiPassword, type));
        if (netId == -1) {
            Toast.makeText(mContext, mContext.getString(R.string.wifi_connect_fail), Toast.LENGTH_LONG).show();
            wifiListAdapter.setConnectingDescription(Bssid, mContext.getString(R.string.wifi_connect_fail));
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.wifi_connecting), Toast.LENGTH_LONG).show();
            wifiListAdapter.setConnectingDescription(Bssid, mContext.getString(R.string.wifi_connecting));
        }
        handler.sendEmptyMessageDelayed(WIFI_INFO, 2000);
        rlWifiConnectingContent.setVisibility(View.GONE);
    }

    private void resetData(List<ScanResult> list) {
        scanResults.clear();
        if (list != null)
            scanResults.addAll(list);
    }

    private void setScanResult() {
        wiFiAdmin.StartScan();
        List<ScanResult> scanResults = wiFiAdmin.GetWifilist();
        resetData(scanResults);
        wifiListAdapter.setConnectedBSSID(getNowWifiBSSID());
//        wifiListAdapter.notifyDataSetChanged();
    }

    private String getNowWifiBSSID() {
        WifiManager mWifi = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = mWifi.getConnectionInfo();
        return wifiInfo.getBSSID();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        dismissDialog();
    }

    @Override
    public void dowhenDismiss() {
        super.dowhenDismiss();
        dismissDialog();
    }

    private void dismissDialog() {
        if (null != refreshWifiTask) {
            refreshWifiTask.cancel();
        }

        if (null != timer) {
            timer.cancel();
        }
        timer = null;
        refreshWifiTask = null;

        brushIntent = new Intent("com.w2here.board.controller_miracast");
        brushIntent.putExtra("is_close_miracast", false);
        mContext.sendBroadcast(brushIntent);
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!buttonView.isPressed())
            return;
        switch (buttonView.getId()) {
            case R.id.tb_auto_ip:
                refreshWiredStatus(!isChecked);
                if (isChecked) { //DHCP
                    Log.e(TAG, "switch to dhcp");
                    ethernetUtil.setDHCPConfiguration();
                }
                rlKeyboard.setVisibility(!isChecked ? View.VISIBLE : View.GONE);
                break;
            case R.id.tb_wifi_switch:
                if (isChecked) {
                    wifiApManager.setWifiApEnabled(null, false);
                    wiFiAdmin.OpenWifi();
                    wiFiAdmin.StartScan();
                    viewWifiNoOpen.setVisibility(View.GONE);
                    rvWifiList.setVisibility(View.VISIBLE);
                    resetData(null);
                    wifiListAdapter.notifyDataSetChanged();
                    handler.sendEmptyMessage(WIFI_SCAN);
                    //关闭以太网
//                    closeEthernet();
                } else {
                    wiFiAdmin.CloseWifi();
                    viewWifiNoOpen.setVisibility(View.VISIBLE);
                    rvWifiList.setVisibility(View.GONE);
                    handler.sendEmptyMessage(WIFI_CLOSE);
                }
                break;
            case R.id.rb_wireless_network:
                if (isChecked) {
                    rbWiredNetwork.setChecked(false);
                    llWirelessNetwork.setVisibility(View.VISIBLE);
                    llWiredNetwork.setVisibility(View.GONE);
                }
                break;
            case R.id.rb_wired_network:
                if (isChecked) {
                    rbWirelessNetwork.setChecked(false);
                    llWirelessNetwork.setVisibility(View.GONE);
                    llWiredNetwork.setVisibility(View.VISIBLE);
                }
                break;
        }
    }


    ////////////////////////////////////// 有线网设置 //////////////////////////////////////////////////

    private static String mEthIpAddress = null;
    private static String mEthNetmask = null;
    private static String mEthGateway = null;
    private static String mEthdns1 = null;
    private static String mEthdns2 = null;
    private final static String nullIpInfo = "0.0.0.0";

//    @Override
//    public void didReceivedNotification(int id, Object... args) {
//        if (id == NotificationCenter.ethernetChanged && args != null) {
//            int etherState = (int) args[0];
//            Log.e(TAG, "以太网状态" + etherState);
//            handleEtherStateChange(etherState);
//        }
//    }

    private void initWired() {
        hideSystemInput(etIpAddress);
        hideSystemInput(etSubnetMask);
        hideSystemInput(etGateway);
        hideSystemInput(etDns1);
        hideSystemInput(etDns2);

        ethernetUtil = new EthernetUtil(mContext);

        tbAutoIp.setOnCheckedChangeListener(this);

        fkKeyboard.setPreviewEnabled(false); // NOTE Do not show the preview balloons
        fkKeyboard.registerEditText(new EditText[]{
                etIpAddress, etSubnetMask, etGateway, etDns1, etDns2});
        fkKeyboard.setSymbolKeyboard();

        etIpAddress.setOnEditorActionListener(this);
        etSubnetMask.setOnEditorActionListener(this);
        etGateway.setOnEditorActionListener(this);
        etDns1.setOnEditorActionListener(this);
        etDns2.setOnEditorActionListener(this);

        etIpAddress.setOnClickListener(this);
        etSubnetMask.setOnClickListener(this);
        etGateway.setOnClickListener(this);
        etDns1.setOnClickListener(this);
        etDns2.setOnClickListener(this);

        tbAutoIp.setChecked(isAutoDhcp());

//        if (BoardUtil.isWirePluggedIn()) {
//            rlCaution.setVisibility(View.GONE);
//        } else {
//            rlCaution.setVisibility(View.VISIBLE);
//        }
        rlCaution.setVisibility(View.GONE);

        refreshWiredStatus(!isAutoDhcp());

        clearCursor();

        handleEtherStateChange(ethernetUtil.getEthernetConnectState());
    }

    //隐藏系统输入法
    private void hideSystemInput(EditText editText) {
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(editText, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean isAutoDhcp() {
        String ipAssignment = ethernetUtil.getIpAssignment();
        if (TextUtils.equals("DHCP", ipAssignment)) {
            return true;
        } else if (TextUtils.equals("STATIC", ipAssignment)) {
            return false;
        }
        return true;
    }

    private void handleEtherStateChange(int EtherState) {
        Log.e(TAG, "curEtherState" + EtherState);
//        if (BoardUtil.isWirePluggedIn()) {
//            rlCaution.setVisibility(View.GONE);
//        } else {
//            rlCaution.setVisibility(View.VISIBLE);
//        }
        if (EtherState == ETHER_STATE_DISCONNECTED) {
            rlCaution.setVisibility(View.VISIBLE);
            mEthIpAddress = nullIpInfo;
            mEthNetmask = nullIpInfo;
            mEthGateway = nullIpInfo;
            mEthdns1 = nullIpInfo;
            mEthdns2 = nullIpInfo;
        } else if (EtherState == ETHER_STATE_CONNECTING) {
            rlCaution.setVisibility(View.GONE);
            String mStatusString = mContext.getString(R.string.ether_getting_ip);
            mEthIpAddress = mStatusString;
            mEthNetmask = mStatusString;
            mEthGateway = mStatusString;
            mEthdns1 = mStatusString;
            mEthdns2 = mStatusString;
        } else if (EtherState == ETHER_STATE_CONNECTED) {
            rlCaution.setVisibility(View.GONE);
            getEthInfo();
        }
        refreshUI();
    }

    private void getEthInfo() {
        if (isAutoDhcp()) {
            getEthInfoFromDhcp();
        } else {
            getEthInfoFromStaticIp();
        }
    }

    private void getEthInfoFromDhcp() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = ethernetUtil.systemPropertiesGet("dhcp." + iface + ".ipaddress");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            mEthIpAddress = tempIpInfo;
        } else {
            mEthIpAddress = nullIpInfo;
        }

        tempIpInfo = ethernetUtil.systemPropertiesGet("dhcp." + iface + ".mask");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            mEthNetmask = tempIpInfo;
        } else {
            mEthNetmask = nullIpInfo;
        }

        tempIpInfo = ethernetUtil.systemPropertiesGet("dhcp." + iface + ".gateway");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            mEthGateway = tempIpInfo;
        } else {
            mEthGateway = nullIpInfo;
        }

        tempIpInfo = ethernetUtil.systemPropertiesGet("dhcp." + iface + ".dns1");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            mEthdns1 = tempIpInfo;
        } else {
            mEthdns1 = nullIpInfo;
        }

        tempIpInfo = ethernetUtil.systemPropertiesGet("dhcp." + iface + ".dns2");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            mEthdns2 = tempIpInfo;
        } else {
            mEthdns2 = nullIpInfo;
        }
    }

    private void getEthInfoFromStaticIp() {
        ContentResolver contentResolver = mContext.getContentResolver();
        mEthIpAddress = Settings.System.getString(contentResolver, ETHERNET_STATIC_IP);
        mEthGateway = Settings.System.getString(contentResolver, ETHERNET_STATIC_GATEWAY);
        mEthNetmask = Settings.System.getString(contentResolver, ETHERNET_STATIC_NETMASK);
        mEthdns1 = Settings.System.getString(contentResolver, ETHERNET_STATIC_DNS1);
        mEthdns2 = Settings.System.getString(contentResolver, ETHERNET_STATIC_DNS2);
    }

    /**
     * 刷新ip地址等
     */
    private void refreshUI() {
        etIpAddress.setText(mEthIpAddress);
        etSubnetMask.setText(mEthNetmask);
        etGateway.setText(mEthGateway);
        etDns1.setText(mEthdns1);
        etDns2.setText(mEthdns2);
    }

    /**
     * 刷新ip地址可编辑和颜色
     */
    private void refreshWiredStatus(boolean isEdit) {

        setEditViewColor(isEdit, etIpAddress, etSubnetMask, etGateway, etDns1, etDns2);

        setEditable(isEdit, etSubnetMask, etGateway, etDns1, etDns2, etIpAddress);
        if (isEdit) {
            etIpAddress.setText("");
            etSubnetMask.setText("");
            etGateway.setText("");
            etDns1.setText("");
            etDns2.setText("");
            etIpAddress.setHint(nullIpInfo);
            etSubnetMask.setHint(nullIpInfo);
            etGateway.setHint(nullIpInfo);
            etDns1.setHint(nullIpInfo);
            etDns2.setHint(nullIpInfo);
        } else {
            etIpAddress.setText(mEthIpAddress);
            etSubnetMask.setText(mEthNetmask);
            etGateway.setText(mEthGateway);
            etDns1.setText(mEthdns1);
            etDns2.setText(mEthdns2);
        }
    }

    private void setEditViewColor(boolean isEdit, EditText... editTexts) {
        for (EditText editText : editTexts) {
            editText.setTextColor(!isEdit
                    ? mContext.getResources().getColor(R.color.color_999999)
                    : mContext.getResources().getColor(R.color.color_333333));
        }
    }

    private void setEditable(boolean isEdit, EditText... editTexts) {
        for (EditText editText : editTexts) {
            if (!isEdit) {
                editText.setFocusable(false);
                editText.setFocusableInTouchMode(false);
                editText.setCursorVisible(false);
            } else {
                editText.setFocusableInTouchMode(true);
                editText.setFocusable(true);
                editText.requestFocus();
                editText.setCursorVisible(true);
            }
        }
    }

    //清除编辑框光标
    private void clearCursor() {
        etIpAddress.setCursorVisible(false);
        etSubnetMask.setCursorVisible(false);
        etGateway.setCursorVisible(false);
        etDns1.setCursorVisible(false);
        etDns2.setCursorVisible(false);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        Log.e(TAG, "onEditorAction");

        if (actionId == EditorInfo.IME_ACTION_DONE) {
            Toast.makeText(mContext, mContext.getString(R.string.connect), Toast.LENGTH_LONG).show();
            final String ipAddress = etIpAddress.getText().toString();
//            final String ipAddress = "192.168.0.254";
            final String netMask = etSubnetMask.getText().toString();
//            final String netMask = "255.255.255.0";
            final String gateway = etGateway.getText().toString();
//            final String gateway = "192.168.0.1";
            final String dns1 = etDns1.getText().toString();
//            final String dns1 = "192.168.0.1";
            final String dns2 = etDns1.getText().toString();
//            final String dns2 = "";

            if (!ethernetUtil.isValidIpAddress(ipAddress)) {
                Toast.makeText(mContext, mContext.getString(R.string.ether_input_ip_error), Toast.LENGTH_LONG).show();
                return false;
            }
            if (!ethernetUtil.isValidNetMask(netMask)) {
                Toast.makeText(mContext, mContext.getString(R.string.ether_input_mask_error), Toast.LENGTH_LONG).show();
                return false;
            }
            if (!ethernetUtil.isValidIpAddress(gateway)) {
                Toast.makeText(mContext, mContext.getString(R.string.ether_input_gateway_error), Toast.LENGTH_LONG).show();
                return false;
            }
            if (!ethernetUtil.isValidIpAddress(dns1)) {
                Toast.makeText(mContext, mContext.getString(R.string.ether_input_dns1_error), Toast.LENGTH_LONG).show();
                return false;
            }
            if (!TextUtils.isEmpty(dns2)) {
                if (!ethernetUtil.isValidIpAddress(dns2)) {
                    Toast.makeText(mContext, mContext.getString(R.string.ether_input_dns2_error), Toast.LENGTH_LONG).show();
                    return false;
                }
            }
            mEthIpAddress = ipAddress;
            mEthNetmask = netMask;
            mEthGateway = gateway;
            mEthdns1 = dns1;
            mEthdns2 = dns2;
            BoardUtil.getCachedThreadPool().submit(new Runnable() {
                @Override
                public void run() {
                    ethernetUtil.setStaticConfig(true, ipAddress, netMask, gateway, dns1, dns2);
                }
            });
            clearCursor();
            rlKeyboard.setVisibility(View.GONE);
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v instanceof EditText && !isAutoDhcp()) {
            if (rlKeyboard.getVisibility() == View.VISIBLE) return;
            if (isAutoDhcp()) return;
            //置于编辑状态，显示键盘
            EditText editText = (EditText) v;
            editText.setText("");
            editText.setHint(nullIpInfo);
            setEditable(true, editText);
            if (rlKeyboard.getVisibility() != View.VISIBLE)
                rlKeyboard.setVisibility(View.VISIBLE);
        }
    }

//    @Override
//    public void onDismiss() {
//        super.onDismiss();
//        if (rlKeyboard.getVisibility() == View.VISIBLE) {
//            clearCursor();
//            rlKeyboard.setVisibility(View.GONE);
//        }
//    }

    public void closeWifi() {
        tbWifiSwitch.setChecked(false);
        wiFiAdmin.CloseWifi();
        viewWifiNoOpen.setVisibility(View.VISIBLE);
        rvWifiList.setVisibility(View.GONE);
        handler.sendEmptyMessage(WIFI_CLOSE);
    }

}
